/**
 * @file	Main.c
 * @purpose	Application code for running on an BLDC motor on the LPC1700
 * @brief	Main file for the BLDC motor control application
 * @version	1.0
 * @date	15 July 2009
 * @author	nlv15840
*/
#include "Application.h"
#include "debug_frmwrk.h"
#include "lpc17xx_can.h"
#include "lpc17xx_libcfg.h"
#include "lpc17xx_pinsel.h"
/************************** APPLICATION VARIABLES *********************/
/**
 * @addtogroup APPLICATION_VARIABLES
 * @{
 */
#define TX_BUFFER_SIZE				1
#define RX_BUFFER_SIZE				3
#define BUFSIZE				0x40
/** SysTick Counter                  */


volatile uint16_t Speed;
extern volatile uint16_t BufferReset_flag;
extern volatile uint32_t UART0Count;
extern volatile uint8_t  UART0Buffer[BUFSIZE],ti;
volatile uint32_t SysTickCnt=0,i,full;
uint8_t Data[10][44];
volatile uint8_t UartCount=0 ;
volatile uint8_t Qdata[5] ;
/** UART ring buffer */

UART_RING_BUFFER_T rb;

/* */
//extern volatile PIDstr PID_Motor;


void QEI_IRQHandler (void)
{
	/* Clear the timer interrupt */
	QEI_IntClear(QEI,QEI_INTFLAG_TIM_Int);
	
	/* Calculate the RPM using Systick */
	 //PID_Motor.RPM=QEI_CalculateRPM(QEI);
	//Speed=(100 * QEI->QEIPOS * 60) / (400 * 4);
	Speed = QEI->QEIPOS ;
	
	Qdata[3] = '0'+ Speed%10;
	Qdata[2] = '0'+((Speed/10)%10);
	Qdata[1] = '0'+((Speed/100)%10);
	Qdata[0] = '0'+((Speed/1000)%10);
	
	/* Re-enable QEI timer interrupt */
	QEI->QEICON = (1<<1);
    return;
}

void SysTick_Handler (void) 
{           /* SysTick Interrupt Handler (1ms)    */
  SysTickCnt++;
  
}

#ifdef  DEBUG
/*******************************************************************************
* @brief		Reports the name of the source file and the source line number
* 				where the CHECK_PARAM error has occurred.
* @param[in]	file Pointer to the source file name
* @param[in]    line assert_param error line source number
* @return		None
*******************************************************************************/
void check_failed(uint8_t *file, uint32_t line)
{
	/* User can add his own implementation to report the file name and line number,
	 ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
	/* Infinite loop */
	while(1);
}
#endif
void UART0_IRQHandler (void)
{
// process_int();
//_DBG("a\n");
} 

void UART2_IRQHandler (void)
{
 process_int();
//_DBG("a\n");

}  

void Call_1(void)
{						 	

	 //UART_IntConfig(UART2, UART_INTCFG_RBR, DISABLE);
	 
	 //UART_Send( UART0, Data,44, BLOCKING);
//	_DBD16( Speed);
//	_DBG("\n");


	 //UART_IntConfig(UART2, UART_INTCFG_RBR, ENABLE);

}

void Call_10ms(void)
{						 	

	 //UART_IntConfig(UART2, UART_INTCFG_RBR, DISABLE);
	 
	 UART_Send( UART0,Qdata,5, BLOCKING);
	// _DBD16( Speed);
	 

	 //UART_IntConfig(UART2, UART_INTCFG_RBR, ENABLE);
	 //_DBD16(BufferReset_flag);
    // BufferReset_flag=0;

}


void BLDC_Init (void)
{
#if (USE_QEI == 1)
	/* QEI configuration structure variable */
	QEI_CFG_Type QEIConfigStruct;

#endif

    /* MCPWM INITIALIZATION *******************************************/
  	//dua gia tri setup tren vao thanh ghi cua chanel[0]

#if (USE_QEI == 1)
	/* QEI CONFIGURATION **********************************************/
	/* Configure the QEI */
	QEIConfigStruct.CaptureMode = QEI_CAPMODE_4X;
	QEIConfigStruct.DirectionInvert = QEI_DIRINV_NONE;//QEI_DIRINV_CMPL;//
	QEIConfigStruct.InvertIndex = QEI_INVINX_NONE;
	QEIConfigStruct.SignalMode = QEI_SIGNALMODE_QUAD;
	/* Initialize the QEI */
	QEI_Init(QEI, &QEIConfigStruct);
	/* Set the QEI Filter clock counter*/
	QEI_SetDigiFilter(QEI, 20);
	/* Set the max QEI position */
//	QEI_SetMaxPosition(QEI, 2000);
	QEI->QEICON = (1<<1);

	/* Enable interrupt for velocity Timer overflow for capture velocity into Acc */
	QEI_IntCmd(QEI, QEI_INTFLAG_TIM_Int, ENABLE);
	/* preemption = 1, sub-priority = 1 */
	NVIC_SetPriority(QEI_IRQn, ((0x01<<3)|0x01));
	/* Enable interrupt for QEI  */
	NVIC_EnableIRQ(QEI_IRQn);

#endif // END OF USE_QEI


}


void initApplication (void)
{
    /* UART Configuration structure variable */
    UART_CFG_Type UARTConfigStruct;
    /* UART FIFO configuration Struct variable */
    //UART_FIFO_CFG_Type UARTFIFOConfigStruct;

    /* Pin configuration for UART0 */
    PINSEL_CFG_Type PinCfg;

    /* SYSTICK CONFIGURATION ******************************************/
    /* Generate interrupt each 1 ms */
    SysTick_Config(SysTick_VALUE);

    /* LED CONFIGURATION **********************************************/
    /* LEDs defined as Output		*/
    FIO_SetDir(0, 1<<20, 1);

    /* UART CONFIGURATION *********************************************/
    /* Initialize UART0 pin connect */
    PinCfg.Funcnum = 1;
    PinCfg.OpenDrain = 0;
    PinCfg.Pinmode = 0;
    PinCfg.Pinnum = 2;
    PinCfg.Portnum = 0;
    PINSEL_ConfigPin(&PinCfg);
    PinCfg.Pinnum = 3;
    PINSEL_ConfigPin(&PinCfg);

	//uart 2
	PinCfg.Funcnum = 1;
    PinCfg.OpenDrain = 0;
    PinCfg.Pinmode = 0;
    PinCfg.Pinnum = 10;
    PinCfg.Portnum = 0;
    PINSEL_ConfigPin(&PinCfg);
    PinCfg.Pinnum = 11;
    PINSEL_ConfigPin(&PinCfg);

    /* Initialize UART Configuration parameter structure to default state:
    * Baudrate = 115200bps
    * 8 data bit
    * 1 Stop bit
    * None parity
    */
	UARTConfigStruct.Baud_rate =115200;
	UARTConfigStruct.Databits = UART_DATABIT_8;
	UARTConfigStruct.Parity = UART_PARITY_NONE;
	UARTConfigStruct.Stopbits = UART_STOPBIT_1;

    /* Initialize UART0 peripheral with given to corresponding parameter */
    UART_Init(UART0, &UARTConfigStruct);
	UART_Init(UART2, &UARTConfigStruct);
    /* Initialize FIFOConfigStruct to default state:
    *        - FIFO_DMAMode = DISABLE
    *        - FIFO_Level = UART_FIFO_TRGLEV0
    *        - FIFO_ResetRxBuf = ENABLE
    *        - FIFO_ResetTxBuf = ENABLE
    *        - FIFO_State = ENABLE
    */
//    UART_FIFOConfigStructInit(&UARTFIFOConfigStruct);

    /* Initialize FIFO for UART0 peripheral */
//    UART_FIFOConfig(UART0, &UARTFIFOConfigStruct);

    /* Configure the UART0 interrupt, enable the RBR interrupt */
    
   // UART_IntConfig(UART0, UART_INTCFG_THRE,ENABLE);
    /* Set the Receive callback */
//	UART_SetupCbs(UART0, 0, (void *)UART0_IntReceive);

	/* Reset ring buf head and tail idx */
	__BUF_RESET(rb.rx_head);
	__BUF_RESET(rb.rx_tail);
	__BUF_RESET(rb.tx_head);
	__BUF_RESET(rb.tx_tail);

    /* preemption = 1, sub-priority = 1 */
    NVIC_SetPriority(UART2_IRQn, ((0x01<<3)|0x01));
	/* Enable Interrupt for UART0 channel */
    NVIC_EnableIRQ(UART0_IRQn);
	NVIC_EnableIRQ(UART2_IRQn);
	UART_IntConfig(UART0, UART_INTCFG_RBR, ENABLE);
	UART_IntConfig(UART2, UART_INTCFG_RBR, ENABLE);
    /* Enable UART Transmit */
    UART_TxCmd(UART0, ENABLE);

	/* Print the welcome message */
//    printf("Welcome to the LPC1700 BLDC Motor Control Demo\n");
	  
    /* BLDC MOTOR CONTROL CONFIGURATION *******************************/
     BLDC_Init ();
	 
    return;
}
/***********************************************************************//**
* @brief	Main BLDC motor control function
***********************************************************************/
int main (void) 
{
   
  DWORD cnt_1ms=0, cnt_10ms=0;
   uint32_t result;
   PINSEL_CFG_Type PinCfg;
  /** Initialize the clocks */
  SystemInit ();
  NVIC_DeInit();
  NVIC_SCBDeInit();
  Qdata[4] ='\n';
  /* Configure the NVIC Preemption Priority Bits:
   * two (2) bits of preemption priority, six (6) bits of sub-priority.
   * Since the Number of Bits used for Priority Levels is five (5), so the
   * actual bit number of sub-priority is three (3)
   */
 	 NVIC_SetPriorityGrouping(0x05);
	debug_frmwrk_init();
	

	/* Pin configuration
	 * CAN1: select P0.0 as RD1. P0.1 as TD1
	 */
	PinCfg.Funcnum = 1;
	PinCfg.OpenDrain = 0;
	PinCfg.Pinmode = 0;
	PinCfg.Pinnum = 0;
	PinCfg.Portnum = 0;
	PINSEL_ConfigPin(&PinCfg);
	PinCfg.Pinnum = 1;
	PINSEL_ConfigPin(&PinCfg);
	
	

	/* Test Acceptance Filter with a simple AF Look-up Table. It just has two sections:
	 * 		- Explicit Standard Frame Format Identifier Section
	 * 		- Explicit Extended Frame Format Identifier Section
	 * We use 4 Message:
	 * 		- 1 Message with 11-bit ID which exit in AF Look-up Table
	 *  	- 1 Message with 11-bit ID which not exit in AF Look-up Table
	 *  	- 1 Message with 29-bit ID which exit in AF Look-up Table
	 *  	- 1 Message with 29-bit ID which not exit in AF Look-up Table
	 *  to check Acceptance filter operation of CAN
	 */

  //  Set Vector table offset value
   #if (__RAM_MODE__==1)
  NVIC_SetVTOR(0x10000000);
  #else
  NVIC_SetVTOR(0x00000000);
  #endif
  /* End of Expansion statement ------------------------------------------------ */

  /* Initialize the current application */
  initApplication();
  /* Enable the BLDC motor */
 // BLDC_Enable();
  _DBG("wellcome to uart test: \n");
  
  
  GPIO_SetDir(0,1<<16,1);
  GPIO_ClearValue(0,1<<16);
  GPIO_SetDir(0,1<<22,1);
  GPIO_ClearValue(0,1<<22);
  while (1)
  {    
      //if ( SysTickCnt >= cnt_1ms )      {cnt_1ms = SysTickCnt+1;      Call_10ms();}
     //if ( SysTickCnt >= cnt_10ms )     {cnt_10ms = SysTickCnt+2;    Call_10ms();}	  //  if(ti==1)
     // if ( SysTickCnt >= cnt_100ms )    {cnt_100ms = SysTickCnt+100;  Call_10ms();}
    // if ( SysTickCnt >= cnt_1s )       {cnt_1s = SysTickCnt+1000;    Call_1s();}
//	_DBD16(Speed);
//	_DBG("\n");
//	for(int i=0;i<=100000;i++)
	 //;
/*	 while(!Rev_flag)
	 {
	 }
	 UART_IntConfig(UART2, UART_INTCFG_RBR, DISABLE);
	 UART_Send( UART0, Data,44, BLOCKING);
	 _DBD16(Speed);
	 _DBG("\n");
     UART_IntConfig(UART2, UART_INTCFG_RBR, ENABLE);
	 Rev_flag= 0;     */
  // UARTPutChar (UART0,Speed%10);
  }
}

/*********************************************************************//**
* @brief  Enters main if called
***********************************************************************/
int c_entry(void)
{
	return main();
}


void UARTCheck(uint8_t input)
{	

if(input=='\n')
 
  {
  //UARTPutChar(UART0,'0'+Qdata[0]);
  //UARTPutChar(UART0,'0'+Qdata[1]);
  //UARTPutChar(UART0,'0'+Qdata[2]);
  //UARTPutChar(UART0,'0'+Qdata[3]);
  UART_Send( UART0,Qdata,5, BLOCKING);	 
   //Rev_flag =1
 //  UartCount ;
 //  full=1;
 //  Call_1();
   
 }
else

//Data[UartCount++]=input;
//UARTPutChar(UART0,input);
UART_SendData(UART0, input); 

}
// UARTPutChar(UART0,input);
 

  //_DBD16(UartCount++);
 //if(input == 0x0A)
 //{
 //UARTPutChar (UART0,Speed%10);
//	UARTPutChar(UART0,input)	;
   	//_DBD16( Speed);
//	_DBG("\n");
 // }
 // else
  // UARTPutChar(UART0,input)	;
  //uint32_t i,result;
	


 

 
